import java.io.*;
//keycodes from:
// http://www.guidingtech.com/15008/adb-control-keypress-broken-android-keys/
//and:  https://developer.android.com/reference/android/view/KeyEvent.html
public class mcp 
  {
  static String keyList[]={null,"menu","soft_right","home","back","call","end_call","0","1","2","3","4","5","6","7","8","9","*","#","up","down","left","right","center","vol+","vol-","pwr","cam","clr","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",",","."};
  static int keycode=0;
  static int x=0;
  static String sAdbPath;
  name2pak n2p =new name2pak();

  String adbPath=null;

  public mcp(String path){
	 adbPath=path;
	 sAdbPath=path;
  }
  
  /**
   * 
   * @param name - apps short name
   * takes the applications short name,
   * and converts it into the long name (via n2p) and
   * runs it on the device
   */
  
  public void startApp(String name){
	String longName= n2p.getpak(name);
	  adb("shell am start -a android.intent.action.MAIN -n "+longName); //convert the apps name to package format, then pass it to adb along with the launch command.
  }
  /**
   * 
   * @param path - Path to ADB
   * Changes the location of ADB.
   */
  public void setPath(String path){
	 adbPath=path;
   }
   
  
  /**
   * 
   * @param rem - Location of file on device
   * @param loc -  Location of where to store the file
   * Pulls file from device, and saves it on the PC
   * 
   */
   public void pull(String rem,String loc){
	   adb("pull "+rem+" "+loc);
   }
   
   
   /**
    * 
    * @param loc - Local File to be sent to device
    * @param rem - Where the file will be stored
    * Send File to Device from PC
    * 
    */
   public void push(String loc,String rem){
	   adb("push "+loc+" "+rem);
   }
   
   
   /**
    * Reboot the Device
    * 
    */
   public void reboot(){
   adb("shell reboot");
   }
   
   
   /**
    * Reboot the device into the bootloader/Recovery
    * 
    */
   public void rebootRec(){
   adb("reboot bootloader");
   }
   /**
    * 
    * 
    * @param path2apk - Path to the file that will be installed
    * Installs File to device
    */
   public void download(String path2apk){
	   
	   adb("install "+path2apk);
	   }
   
   public void reAdb(){
	  adb("kill-server");
	  adb("start-server");
   }
   
   /**
    * 
    * @param host - Port on Device
    * @param client -Port on Computer
    * Forwards a port from the device
    * to the computer.
    * 
    */ 
  	public void prtFwd(int host,int client){//port forwarding
	
		adb("forward tcp:"+client+" tcp:"+host);
  	}
  	
  	
  	/**
  	 * 
  	 * @param key - Keypress to send to device
  	 * 
  	 * Accepts keypresses, and sends them to the device.
  	 * It can accept letters/numbers but 'sendtext'
  	 * is better for that, this is more for special keys,
  	 * such as 'Power' and the arrow keys
  	 * 
  	 */
	public static void sendkey(String key){//I'll keep the old (full)method for passing a adb command
									//because I'm gonna figure out how to make it go faster.
		x=0;
		keycode=0;
		//eliminate the extra keys
		if (key.equals(" ")){
			x=62;}
		if (key.equals("mute")){
			x=91;				
			}
		
		if (key.equals("enter")){
		x=66;				
		}
		
		if (key.equals("backsp")){
			x=67;}			
		
		if (x<56){
			while ((!key.equals(keyList[x]))) {//look for the passed string 'key' in the keyList
			x++;
			if (x>56)
				break;
			}//once we've found it, we can stop looking, x will be it's location,
			//x will also be the key code we need for ADB
		}

		
		keycode=x;
		try {
			final Process snd = Runtime.getRuntime().exec(sAdbPath+" shell input keyevent "+keycode);
			Thread.sleep(600);
			//int exit =snd.waitFor();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	} catch (InterruptedException e) {
		//	 TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @param url - the URL to be opened on the device
	 * Opens a web link on the users device.
	 * If the user fails to add http:// or ftp://
	 * it will be added for them.
	 * 
	 */
	public void openPage(String url)
	{
	if ((url.indexOf("http://")==-1)&&(url.indexOf("https://")==-1)&&(url.indexOf("ftp://")==-1)&&(url.indexOf("sftp://")==-1))
		url="http://"+url;//if the url dose not contain http/ftp or the secure version, assume http.
	adb("shell am start -a android.intent.action.VIEW  "+url);
	}
	
	
	/**
	 * 
	 * @param line - Single Line of text to be send to device
	 * Lines will be split on spaces, since only single words can be sent.
	 * 
	 */
	public void sendText(String line){
		String[] lines = line.split(" ");
		for (String singlLine : lines){
			adb("shell input text "+singlLine);
			sendkey(" ");
			}
	}
	/**
	 * 
	 * @param command - Command to pass to adb
	 * @return error code 0=none, -1 =no devices found,
	 */
	private int adb(String command){
		InputStream stdin;
		
		String conOutput = "";//A string that will hold the console's read and buffered output.
		String snglLine=null;//a single line read from out output, will be added to out full output 'conOutput'
		
		   try {
				final Process snd = Runtime.getRuntime().exec(adbPath+" "+command);
				//--Get console output
				stdin = snd.getInputStream();//Makes an inputString 'stdin' that will contain the data from adb's output
				InputStreamReader adbRead = new InputStreamReader(stdin); //This InputStreamReader will read the data from out new inputString 'stdin'
				BufferedReader buffRead = new BufferedReader(adbRead);// 'buffRead will be the buffer for our InputStreamReader
				while ( (snglLine = buffRead.readLine()) != null){
	                System.out.println(snglLine);
	                conOutput=conOutput+snglLine+"\n";
					}
				
	           if(!(conOutput.indexOf("device not found")==-1)){//if the text "error: device not found" is in the output,
	        	   System.err.println("ERROR: device not found\n Please make sure your device is Turned  on\n"+ //Then tell the user
	        			 "And has USB Debugging Enabled.");
	        	   return (-1);
	        	   }
	           
	            int exitVal = snd.waitFor();
				//--end of console output get
	            
			} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
			} catch (InterruptedException e) {
				//	 TODO Auto-generated catch block
					e.printStackTrace();
				}
		 System.out.println(conOutput);
		return 0;//if nothing went wrong.
	   }
	

}